<?php
//树形结构转换为数组
function tree_to_list( $tree , $child = '_child'){
    $res = array();
    if( is_array( $tree) ){
        foreach( $tree as $_v)
        {
            if( isset( $_v[$child]) && count( $_v[$child]))
            {
                $res = array_merge( $res , tree_to_list( $_v[$child] , $child ) );
            }
            unset( $_v[$child]);
            $res[] = $_v;
        }
    }
    else{
        if( isset( $tree[$child]) && count( $tree[$child])){
                $res = array_merge( $res , tree_to_list( $tree[$child] , $child ) );
        }
        unset( $tree[$child]);
        $res[] = $tree;
    }
    return $res;
}

//数组转换为树形结构
function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0){
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

// 获取部门及上级部门id
function GetParentSector($data,$sectorid){
	static  $arr = array();
	if($data && $sectorid){
		$arr[] = $sectorid;
		foreach($data as $key =>$val){
			if($val['sector_id'] == $sectorid && $sectorid != 0){
				if($val['parent_sector']){
					$arr[] = $val['parent_sector'];
				}
				GetParentSector($data,$val['parent_sector']);
			}
		}
	}
	return array_unique($arr);	
} 

// 获取文件最初名字
function GetFName($knowledge_file_id){
	$arr = array('extersion'=>'','name'=>'');
	$callfun = M('knowledge_file')->field('knowledge_file_name,file_original_name')->where(array('knowledge_file_id'=>$knowledge_file_id))->find();
	$extersion = explode('.',basename($callfun['knowledge_file_name']));
	$name = explode('.',$callfun['file_original_name']);
	$arr['extersion'] = $extersion;
	$arr['name'] = $name;
	return $arr;
}

// 文件下载
function DownLoadFile($knowledge_file_id){
	$downfile = M('knowledge_file')->field('knowledge_file_name')->where(array('knowledge_file_id'=>$knowledge_file_id))->find();
	$destination = $downfile['knowledge_file_name'];
	$new_path = __ROOT__.$destination ;
	$real_path = str_replace('\\', '/', $new_path );
	if (!file_exists($real_path) && !is_file($real_path)) 
			die("File not found");
	header('Content-Description: File Transfer');
	header('Content-Type: application/octet-stream');
	header('Content-Disposition: attachment; filename="'.basename($real_path).'"');
	header("Content-Transfer-Encoding: Binary"); 
	header('Expires: 0');
	header('Cache-Control:no-cache, must-revalidate');
	header('Pragma: public');
	header('Content-Length:'.filesize($real_path));
	ob_end_clean(); // Added by me
	ob_start(); // Added by me
	// flush();
	readfile($real_path);
	exit;	
}

// 获取节点路径
// function GetNodePath($knowledge_spot_id){
// 	$arr =  array();
// 	$callfun = M('knowledge_spot')->field('code,name')->where(array('knowledge_spot_id'=>$knowledge_spot_id))->find();
// 	if($callfun){
// 		$num  = strlen($callfun['code'])/2;
// 		if($num == 1){
// 			$code = $callfun['name'];
// 		}else{
// 			for($i=1;$i<=$num;$i++ ){
// 				$arr[] = substr($callfun['code'],0,$i*2); 
// 			}
// 			$callfuncode = M('knowledge_spot')->field('name')->where(array('code'=>array('IN',$arr)))->select();
// 			foreach($callfuncode as $key=>$val){
// 				if($key == 0){
// 					$code = $val['name'];
// 				}else{
// 					$code = $code.'>>'.$val['name'];
// 				}
// 			}				
// 		}
// 	}	
// 	return $code;
// }

// 获取节点路径
function GetNodePath($knowledge_spot_id,$user_id,$sector_id,$right){
	$arr = $knowledgeSpotId = $callback = $callname =  array();
	$callfun = M('knowledge_spot')->field('code,name')->where(array('knowledge_spot_id'=>$knowledge_spot_id))->find();
	if($callfun){
		$num  = strlen($callfun['code'])/2;
		if($num == 1){
			$code = $callfun['name'];
		}else{
			for($i=1;$i<=$num;$i++ ){
				$arr[] = substr($callfun['code'],0,$i*2); //will exist  values in repeat
			}
			if($right){
				$callfuncode = M('knowledge_spot')->field('name')->where(array('code'=>array('IN',$arr),'is_delete'=>array('neq',1)))->order('code asc')->select();
				if($callfuncode){
					foreach($callfuncode as $key=>$val){
						if($key == 0){
							$code = $val['name'];
						}else{
							$code = $code.'>>'.$val['name'];
						}
					}						
				}
			}else{
				$callfuncode = M('knowledge_spot')->field('knowledge_spot_id')->where(array('code'=>array('IN',$arr),'is_delete'=>array('neq',1)))->order('code asc')->select();
				foreach($callfuncode as $key=>$val){
					$callfunres = GetKnowledgeDataInRight($val['knowledge_spot_id'],$user_id,$sector_id);
					if($callfunres){
						$callback[] = $val['knowledge_spot_id'];
					}
				}
				if($callback){
					$callname = M('knowledge_spot')->field('name')->where(array('knowledge_spot_id'=>array('IN',$callback)))->order('code asc')->select();
				}
				if($callname){
					foreach($callname as $k=>$v){
						if($k == 0){
							$code = $v['name'];
						}else{
							$code = $code.'>>'.$v['name'];
						}
					}					
				}
			}
		}
	}
	return $code;
}


// get knowledgeright data
function GetKnowledgeDataInRight($knowledge_spot_id,$user_id,$sector_id){
	$arr = $sec = $user  = array();
		$data = M('sector')->select();
		$callfunsec = GetParentSector($data,$sector_id);
		if($callfunsec){
			$callfunall = M('knowledge_spot_sector_right')->distinct(true)->field('knowledge_spot_id')->where(array('sector_id'=>array('IN',$callfunsec)))->select();
		}
		if($callfunall){
			foreach($callfunall  as $key => $val){
				$sec[] = $val['knowledge_spot_id'];
			}	
			if(!empty($sec)){
				if(in_array($knowledge_spot_id,$sec)){
					$res = $knowledge_spot_id; 
				}else{
					$callfunuser = M('knowledge_spot_user_right')->distinct(true)->field('knowledge_spot_id')->where(array('user_id'=>$user_id))->select();
					if($callfunuser){
						foreach($callfunuser as $kuser =>$vuser){
							$user[] = $vuser['knowledge_spot_id'];
						}
					}
					if(!empty($user)){
						if(in_array($knowledge_spot_id,$user)){
							$res= $knowledge_spot_id; 
						}
					}
				}
			}	
		}
	return $res;	
}

//所属部门、下属部门查找
function list_to_sector($data,$sectorid){

	if(is_array($sectorid)){
		foreach ($sectorid as $k => $val) {
			static $Array= array();
			$Array[$k][] = $val['sector_id'];
			foreach ($data as $key => $value) {
				if ($value['parent_sector'] == $val['sector_id'] &&$value['sector_id'] !=  $val['sector_id']) {//找子类
					$Array[$k][]=$value['sector_id'];
					list_to_sector($data,$value['sector_id']);
				}
			}
		}
		$newArray =	$Array;
	}else{
		static $Object = array();
		$Object[] = $sectorid;
		foreach ($data as $key => $value) {
			if ($value['parent_sector'] == $sectorid &&$value['sector_id'] !=  $sectorid) {//找子类
				$Object[]=$value['sector_id'];
				list_to_sector($data,$value['sector_id']);
			}
		}
		//$list = array_unique($Array);//消除重复项
		$newArray = array();
		foreach (array_unique($Object) as $key=>$value) {
			if(!empty($value)){
				$newArray[$key]['sector_id'] = $value;
			}
		}
	}

	return $newArray;
}

//所属岗位、下属岗位查找
function list_to_role($data,$roleid){
	static $Array = array();
	$Array[] = $roleid;
	foreach ($data as $key => $value) {
		if ($value['parent_role'] == $roleid &&$value['role_id'] !=  $roleid) {//找子类
			$Array[]=$value['role_id'];
			list_to_role($data,$value['role_id']);
		}
	}
	//$list = array_unique($Array);//消除重复项
	$newArray = array();
	foreach (array_unique($Array) as $key=>$value) {
		if(!empty($value)){
			$newArray[$key]['role_id'] = $value;
		}
	}
	return $newArray;
}
//分公司serch
function list_to_company(){
    $where['parent_company'] = '1';
    $res = M("sector")->field("sector_name,sector_id")->where($where)->select();
    foreach ($res as &$value) {
    	$value['sector_name'] = mb_substr($value['sector_name'],0,5,'utf-8');
    }
    $v = count($res)+1;
    $res[$v]['sector_name'] = "总公司";
    $res[$v]['sector_id'] = "";
   	$res = array_reverse($res);
   	return $res;
} 
//产品serch
function list_to_product( $user,$data_admin ){
	$Pproduct = M("product");
	if($data_admin == 0){
		$wheres['sector_id'] = $user['sector_id'];
    	$company = M("sector")->field("parent_company")->where($wheres)->find();
    	if($company['parent_company'] == 1 || $company['parent_company'] == 0){
			$maps['sub_company'] = $user['sector_id'];
			$maps['product_type']= 0;
			$maps['_logic']       = 'OR';
			$res= $Pproduct->field("name,product_id,sub_company")->where($maps)->select();
		}else{
			$maps['sub_company'] = $company['parent_company'];
			$maps['product_type']= 0;
			$maps['_logic']       = 'OR';
			$res= $Pproduct->field("name,product_id,sub_company")->where($maps)->select();
		}
	}else{
		$res= $Pproduct->field("name,product_id,sub_company")->select();
	}

    $vb = count($res)+1;
	$res[$vb]['name'] = "全部产品";
	$res[$vb]['product_id'] = "-1";
	$res = array_reverse($res);
	return $res;
}
/*----- String/Charset Operation -----*/
function e_json( $data ){
	echo json_encode( $data );
	exit();
}

function u2g($str){
	return iconv("UTF-8","GBK",$str);
}

function g2u($str){
	return iconv("GBK","UTF-8//ignore",$str);
}

function ff_letter_first($s0){
	$firstchar_ord=ord(strtoupper($s0{0}));
	if (($firstchar_ord>=65 and $firstchar_ord<=91)or($firstchar_ord>=48 and $firstchar_ord<=57)) return $s0{0};
	$s=iconv("UTF-8","gb2312", $s0);
	$asc=ord($s{0})*256+ord($s{1})-65536;
	if($asc>=-20319 and $asc<=-20284)return "A";
	if($asc>=-20283 and $asc<=-19776)return "B";
	if($asc>=-19775 and $asc<=-19219)return "C";
	if($asc>=-19218 and $asc<=-18711)return "D";
	if($asc>=-18710 and $asc<=-18527)return "E";
	if($asc>=-18526 and $asc<=-18240)return "F";
	if($asc>=-18239 and $asc<=-17923)return "G";
	if($asc>=-17922 and $asc<=-17418)return "H";
	if($asc>=-17417 and $asc<=-16475)return "J";
	if($asc>=-16474 and $asc<=-16213)return "K";
	if($asc>=-16212 and $asc<=-15641)return "L";
	if($asc>=-15640 and $asc<=-15166)return "M";
	if($asc>=-15165 and $asc<=-14923)return "N";
	if($asc>=-14922 and $asc<=-14915)return "O";
	if($asc>=-14914 and $asc<=-14631)return "P";
	if($asc>=-14630 and $asc<=-14150)return "Q";
	if($asc>=-14149 and $asc<=-14091)return "R";
	if($asc>=-14090 and $asc<=-13319)return "S";
	if($asc>=-13318 and $asc<=-12839)return "T";
	if($asc>=-12838 and $asc<=-12557)return "W";
	if($asc>=-12556 and $asc<=-11848)return "X";
	if($asc>=-11847 and $asc<=-11056)return "Y";
	if($asc>=-11055 and $asc<=-10247)return "Z";
	return 0;//null
}

function is_utf8($liehuo_net){
	if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$liehuo_net) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$liehuo_net) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$liehuo_net) == true)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function nb($str){
	$str = str_replace("　",' ',str_replace("&nbsp;",' ',$str));
	$str = ereg_replace("[\r\n\t ]{1,}",' ',$str);
	return trim($str);
}

function msubstr($str, $start=0, $length, $suffix=false){
	return ff_msubstr(eregi_replace('<[^>]+>','',ereg_replace("[\r\n\t ]{1,}",' ',nb($str))),$start,$length,'utf-8',$suffix);
}
function ff_msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
	$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all($re[$charset], $str, $match);
	$length_new = $length;
	for($i=$start; $i<$length; $i++){
		if (ord($match[0][$i]) > 0xa0){
			//中文
		}else{
			$length_new++;
			$length_chi++;
		}
	}
	if($length_chi<$length){
		$length_new = $length+($length_chi/2);
	}
	$slice = join("",array_slice($match[0], $start, $length_new));
    if($suffix && $slice != $str){
		return $slice."…";
	}
    return $slice;
}

/*----------------Encrypt-------------------*/
function md6( $str = ''){
  return md5(md5(md5(md5($str))));
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	$key = md5($key != '' ? $key :  C('SITE_HASH_KEY') );
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}}

//输出安全的html
function h($text, $tags = null){
	$text	=	trim($text);
	//完全过滤注释
	$text	=	preg_replace('/<!--?.*-->/','',$text);
	//完全过滤动态代码
	$text	=	preg_replace('/<\?|\?'.'>/','',$text);
	//完全过滤js
	$text	=	preg_replace('/<script?.*\/script>/','',$text);

	$text	=	str_replace('[','&#091;',$text);
	$text	=	str_replace(']','&#093;',$text);
	$text	=	str_replace('|','&#124;',$text);
	//过滤换行符
	$text	=	preg_replace('/\r?\n/','',$text);
	//br
	$text	=	preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
	$text	=	preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
	//过滤危险的属性，如：过滤on事件lang js
	while(preg_match('/(<[^><]+)( lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1],$text);
	}
	while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1].$mat[3],$text);
	}
	if(empty($tags)) {
		$tags = 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a';
	}
	//允许的HTML标签
	$text	=	preg_replace('/<('.$tags.')( [^><\[\]]*)>/i','[\1\2]',$text);
	//过滤多余html
	$text	=	preg_replace('/<\/?(html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml)[^><]*>/i','',$text);
	//过滤合法的html标签
	while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
		$text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
	}
	//转换引号
	while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
		$text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
	}
	//过滤错误的单个引号
	while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
		$text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
	}
	//转换其它所有不合法的 < >
	$text	=	str_replace('<','&lt;',$text);
	$text	=	str_replace('>','&gt;',$text);
	$text	=	str_replace('"','&quot;',$text);
	 //反转换
	$text	=	str_replace('[','<',$text);
	$text	=	str_replace(']','>',$text);
	$text	=	str_replace('|','"',$text);
	//过滤多余空格
	$text	=	str_replace('  ',' ',$text);
	return $text;
}

function remove_xss($val) {
   $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
   $search = 'abcdefghijklmnopqrstuvwxyz';
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $search .= '1234567890!@#$%^&*()';
   $search .= '~`";:?+/={}[]-_|\'\\';
   for ($i = 0; $i < strlen($search); $i++) {
      $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }
   $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
   $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   $ra = array_merge($ra1, $ra2);
   $found = true; // keep replacing as long as the previous round replaced something
   while ($found == true) {
      $val_before = $val;
      for ($i = 0; $i < sizeof($ra); $i++) {
         $pattern = '/';
         for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
               $pattern .= '(';
               $pattern .= '(&#[xX]0{0,8}([9ab]);)';
               $pattern .= '|';
               $pattern .= '|(&#0{0,8}([9|10|13]);)';
               $pattern .= ')*';
            }
            $pattern .= $ra[$i][$j];
         }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
         if ($val_before == $val) {
            // no replacements were made, so exit the loop
            $found = false;
         }
      }
   }
   return $val;
}

function getip(){
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
       $ip = getenv("HTTP_CLIENT_IP");
   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
       $ip = getenv("REMOTE_ADDR");
   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
       $ip = $_SERVER['REMOTE_ADDR'];
   else
       $ip = "unknown";
   return($ip);
}

/**--------CONSTANT DEFINE-----**/
if( !defined("XML_RIGHT") )
	define("XML_RIGHT",CONF_PATH.'right.xml');

/*电话号码掩码*/
function phone_mask( $phone ,$pad_str = '*')
{
    if ($phone&&is_string($phone)&&strlen($phone)>10) {
        $str = '';
        $pad = str_pad('', 4, $pad_str);
        if(substr($phone, 0, 1) == '0') {
            $str = '0'.substr($phone,1, 3).$pad.substr($phone, 8);
        }
        else {
            $str = substr($phone,0, 3).$pad.substr($phone, 7);
        }
        return $str;
    }
    else
        return '';
}

/**
*将数字金额转换为中文金额
*  注意返回　中文大小金额后面没有单位，默认的单位就元  
* 
*@param $num  float
*
*return string 格式:壹拾贰万捌仟
*/
function num_to_rmb($num) {  
        $c1 = "零壹贰叁肆伍陆柒捌玖";  
        $c2 = "分角元拾佰仟万拾佰仟亿";  
        //精确到分后面就不要了，所以只留两个小数位  
        $num = round($num, 2);   
        //将数字转化为整数  
        $num = $num * 100;  
        if (strlen($num) > 10) {  
                return false;  
        }   
        $i = 0;  
        $c = "";  
        while (1) {  
                if ($i == 0) {  
                        //获取最后一位数字  
                        $n = substr($num, strlen($num)-1, 1);  
                } else {  
                        $n = $num % 10;  
                }  
                //每次将最后一位数字转化为中文  
                $p1 = substr($c1, 3 * $n, 3);  
                $p2 = substr($c2, 3 * $i, 3);  
                if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {  
                        $c = $p1 . $p2 . $c;  
                } else {  
                        $c = $p1 . $c;  
                }  
                $i = $i + 1;  
                //去掉数字最后一位了  
                $num = $num / 10;  
                $num = (int)$num;  
                //结束循环  
                if ($num == 0) {  
                        break;  
                }   
        }  
        $j = 0;  
        $slen = strlen($c);  
        while ($j < $slen) {  
                //utf8一个汉字相当3个字符  
                $m = substr($c, $j, 6);  
                //处理数字中很多0的情况,每次循环去掉一个汉字“零”  
                if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {  
                        $left = substr($c, 0, $j);  
                        $right = substr($c, $j + 3);  
                        $c = $left . $right;  
                        $j = $j-3;  
                        $slen = $slen-3;  
                }   
                $j = $j + 3;  
        }   
        //这个是为了去掉类似23.0中最后一个“零”字  
        if (substr($c, strlen($c)-3, 3) == '零') {  
                $c = substr($c, 0, strlen($c)-3);  
        }  
        return empty($c) ? "零" : msubstr($c,0,-1);  
}  
?>
